import React, {Component} from 'react';
import {Select, Icon, Tooltip, Modal, Button, Tabs} from 'antd';
import moment from 'moment';
import DataTable from '../../components/display/gridTable';
import config from "../../utils/aliconfig";
import {aliLoglist} from '../../fetch/fetchApi';
import AliLogQueryFilter from './alilogfilter';

const Option = Select.Option;
const TabPane = Tabs.TabPane;

const {api} = config;
const {logModule: {logListApi, getLogsApi}} = api;

/**
 *  阿里云日志列表
 */
class AliLogList extends Component {

  state = {
    lastQueryTime: moment().format('x'),
    dataSource: [],
    selectedVal: '',
    visible: false,
    logDetails: [],
    listParams: {},
    fromFilter: false,
    pagination: {
      total: 0,
      pageSize: 20
    },
    loading: !1
  }

  getSystemLogSelect = () => {
    return (
      config.systemLogs.map((systemLog, i) => {
        return <Option value={systemLog.logger} key={systemLog.logger}>{systemLog.application}</Option>
      })
    )
  }

  handleChange = (value) => {
    this.setState({
      selectedVal: value
    });
  }

  reloadTable = () => {
    //刷新列表
    this.setState({
      lastQueryTime: moment().format('x')
    })
  }

  /**
   *  阿里云日志查询筛选
   * */
  onFilterChange = (fields) => {
    fields['page'] = 1;
    fields['pagecount'] = 20;
    this.state.pagination.current = 1;
    this.state.pagination.page = '1';
    this.state.pagination.pagecount = '20';
    this.setState({
      listParams: fields,
      fromFilter: true,
      pagination: this.state.pagination
    }, () => {
      this.queryAliLogList(this.state.listParams);
    });
  }

  queryAliLogList (param) {-
    this.setState({
      loading: !0
    });
    this.getAliLogList(param).then((result) => {
      if (result.code === '200') {
        const pagination = {
          total: result.pageLimit.totalCount,
          onShowSizeChange: (current) => {
            this.turnPage(current)
          },
          onChange:(current) => {
            this.turnPage(current)
          }
        }
        this.setState({
          pagination,
          dataSource: result.data
        });
      }
      this.setState({
        loading: !1
      });
    });
  }

  // 跳转页码
  turnPage (current) {
    this.state.listParams['page'] = current.toString();
    this.setState({
      listParams: this.state.listParams
    });
    this.queryAliLogList(this.state.listParams);
  }

  showModal = (logDetails) => {
    this.setState({
      visible: true,
      logDetails: logDetails
    });
  }

  handleOk = (e) => {
    this.setState({
      visible: false
    });
  }
  handleCancel = (e) => {
    this.setState({
      visible: false
    });
  }

  afterClose = (e) => {
    this.setState({
      logDetails: []
    });
  }

  showLogContent = (logTags, logDetails) => {
    let contents = [];
    if (logTags && logTags.length > 0) {
      logTags.map((item) => {
        if (item != '__topic__:' && new RegExp('^[^\_\_tag].*$').test(item)) {
          contents.push(item)
        }
      })
    }
    if (logDetails && logDetails.length > 0) {
      logDetails.map((item) => {
        contents.push(item)
      })
    }
    return contents
  }

  // 查询日志列表
  async getAliLogList (param) {
    try {
      const resData = await aliLoglist(param);
      return resData.data;
    } catch (e) {
      console.log(e);
    }
  }

  render() {

    const columns = [{
      title: "Source",
      dataIndex: "source",
      key: "source",
      width: 120
    }, {
      title: "Tags",
      dataIndex: "logTags",
      key: "logTags",
      width: 300,
      render: (text, record) => {
        if (record['logTags'] && record['logTags'].length > 0) {
          return (<div>
            {
              record['logTags'].map((item) => {
                return <p key={item}>{item}</p>
              })
            }
          </div>)
        } else {
          return ''
        }
      }
    }, {
      title: "描述",
      dataIndex: "logDetails",
      key: "logDetails",
      render: (text, record) => {
        if (record.logDetails && record.logDetails.length > 0) {
          return <p className="two-line-text-wrapper">
            {text}
          </p>
        } else {
          return ''
        }
      }
    }, {
      title: "操作",
      dataIndex: "id",
      key: "id",
      width: 50,
      render: (text, record) => {
        if (record.logDetails && record.logDetails.length > 0) {
          return <Button size="small" type='primary' onClick={() => {
            this.showModal(record.logDetails)
          }}>详情</Button>
        } else {
          return ''
        }
      }
    }];

    const columnsForSdk = [{
      title: "时间",
      dataIndex: "logTimeFmt",
      key: "logTimeFmt",
      width: 135
    }, {
      title: "Source",
      dataIndex: "source",
      key: "source",
      width: 90
    }, {
      title: "日志内容",
      dataIndex: "logDetails",
      key: "logDetails",
      render: (text, record) => {
        const logContents = this.showLogContent(record.logTags, record.logDetails);
        if (logContents && logContents.length > 0) {
          return (<div>
            {
              logContents.map((item) => {
                return <p key={item}>{item}</p>
              })
            }
          </div>)
        } else {
          return ''
        }
      }
    }];

    const dataSource = this.state.dataSource;

    const modalVisibility = this.state.visible;
    const detailArray = this.state.logDetails;
    return (
        <div>
          <AliLogQueryFilter onFilterChange={this.onFilterChange}/>
          <br/>
          <DataTable columns={columnsForSdk} data={dataSource} loading={this.state.loading}
                     pagination={this.state.pagination} autoLoad={false}/>
        </div>
    );
  }
}

export default AliLogList;